/**
 * 
 */
package com.android.backup;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.android.contacts.model.ContactsConstants;
import com.android.utility.Utils;

/**
 * @author Amit
 * 
 */
public class ReadContactsActivity extends Activity {

	private String mID;
	private String mLookupKey;
	private String mName;
	private String mStreet;
	private String mCity;
	private String mState;
	private String mPostCode;
	private String mCountry;
	private String mPhone[];
	private String mPhoneType[];
	private String mEmail[];
	private String mEmailType[];
	private File mRoot;
	private int mEmailCounter;
	private int mPhoneCounter;
	private int mAddCounter;
	private TextView mTextView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contacts);
		mTextView = (TextView) findViewById(R.id.textView);

		// Allow for up to 5 email and phone entries for a contact.
		mEmail = new String[5];
		mEmailType = new String[5];
		mPhone = new String[5];
		mPhone = new String[5];

		// check if the external media available and writable.
		if (Utils.checkExternalMedia()) {
			// TODO : add dialog box no media available;
		}
		accessContacts();
	}

	private void accessContacts() {
		File dir = new File(Utils.getExternalStorageRoot() + "/download");
		dir.mkdirs();
		File file = new File(dir, "phoneData.txt");
		mTextView.append("Wrote " + file + "\nfor following contacts:\n");

		try {
			FileOutputStream f = new FileOutputStream(file);
			PrintWriter pw = new PrintWriter(f);
			ContentResolver contentResolver = getContentResolver();
			Cursor cursor = contentResolver.query(ContactsConstants.URI, null,
					null, null, null);

			if (cursor.getCount() > 0) {

				// Loop all over contacts
				while (cursor.moveToNext()) {
					// Initialize storage variables for the new contact
					mStreet = "";
					mCity = "";
					mState = "";
					mPostCode = "";
					mCountry = "";

					// Get ID information (id, name and lookup key) for this
					// contact. id is an identifier number, name is the name
					// associated with this row in the database, and
					// lookupKey is an opaque value that contains hints on how
					// to
					// find the contact if its row id changed as a result of a
					// sync
					// or aggregation.

					mID = Utils.getColumnValue(cursor, ContactsConstants.ID);
					mName = Utils.getColumnValue(cursor,
							ContactsConstants.DNAME);
					mLookupKey = Utils.getColumnValue(cursor,
							ContactsConstants.LOOKY);
					// Append list of contacts to the scrollable TextView on the
					// screen.
					mTextView.append("\n" + mID + " " + mName);

					// Query phone numbers for this contact (may be more than
					// one),
					// so use a while-loop to move the cursor to the next row
					// until
					// moveToNext() returns false, indicating no more rows.
					// Store
					// the results in arrays since there may be more than one
					// phone
					// number stored per contact. The if-statement enclosing
					// everything ensures that the contact has at least one
					// phone
					// number stored in the Contacts database.
					getPhoneNumbers(cursor, contentResolver, mID);

					// Query email addresses for this contact (may be more than
					// one), so use a while-loop to move the cursor to the next
					// row
					// until moveToNext() returns false, indicating no more
					// rows.
					// Store the results in arrays / since there may
					// be more than one email address stored per contact.
					getEmailAddress(cursor, contentResolver, mID);

					// Query Address (assume only one address stored for
					// simplicity). If there is more than one address we loop
					// through all with the while-loop but keep only the last
					// one.
					getAddress(cursor, contentResolver, mID);

					// Write identifiers for this contact to the SD card file
					pw.println(mName + " ID=" + mID + " LOOKUP_KEY="
							+ mLookupKey);
					// Write list of phone numbers for this contact to SD card
					// file
					for (int i = 0; i < mPhoneCounter; i++) {
						pw.println("   phone=" + mPhone[i] + " type="
								+ mPhoneType[i] + " ("
								+ getPhoneType(mPhoneType[i]) + ") ");
					}
					// Write list of email addresses for this contact to SD card
					// file
					for (int i = 0; i < mEmailCounter; i++) {
						pw.println("   email=" + mEmail[i] + " type="
								+ mEmailType[i] + " ("
								+ getEmailType(mEmailType[i]) + ") ");
					}
					// If street address is stored for contact, write it to SD
					// card
					// file
					if (mAddCounter > 0) {
						if (mStreet != null)
							pw.println("   street=" + mStreet);
						if (mCity != null)
							pw.println("   city=" + mCity);
						if (mState != null)
							pw.println("   state/region=" + mState);
						if (mPostCode != null)
							pw.println("   postcode=" + mPostCode);
						if (mCountry != null)
							pw.println("   country=" + mCountry);
					}
				}

			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			Log.i("MEDIA",
					"*************** File not found. Did you"
							+ " add a WRITE_EXTERNAL_STORAGE permission to the manifest file? ");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String getEmailType(String index) {
		if (index.trim().equals("1")) {
			return "home";
		} else if (index.trim().equals("2")) {
			return "mobile";
		}
		if (index.trim().equals("3")) {
			return "work";
		}
		if (index.trim().equals("7")) {
			return "other";
		} else {
			return "?";
		}
	}

	private String getPhoneType(String index) {
		if (index.trim().equals("1")) {
			return "home";
		} else if (index.trim().equals("2")) {
			return "mobile";
		}
		if (index.trim().equals("3")) {
			return "work";
		}
		if (index.trim().equals("4")) {
			return "other";
		} else {
			return "?";
		}
	}

	private void getPhoneNumbers(Cursor cursor,
			ContentResolver contentResolver, String id) {
		mPhoneCounter = 0;
		if (Integer.parseInt(Utils
				.getColumnValue(cursor, ContactsConstants.HPN)) > 0) {
			cursor = contentResolver.query(ContactsConstants.PURI, null,
					ContactsConstants.CID + " = ? ", new String[] { id }, null);
			while (cursor.moveToNext()) {
				mPhone[mPhoneCounter] = Utils.getColumnValue(cursor,
						ContactsConstants.PNUM);
				mPhoneType[mPhoneCounter] = Utils.getColumnValue(cursor,
						ContactsConstants.PHONETYPE);
				mPhoneCounter++;
			}
		}
		cursor.close();
	}

	private void getEmailAddress(Cursor cursor,
			ContentResolver contentResolver, String id) {
		mEmailCounter = 0;
		cursor = contentResolver.query(ContactsConstants.EURI, null,
				ContactsConstants.EID + " = ? ", new String[] { id }, null);
		while (cursor.moveToNext()) {
			mEmail[mEmailCounter] = Utils.getColumnValue(cursor,
					ContactsConstants.EMAIL);
			mEmailType[mEmailCounter] = Utils.getColumnValue(cursor,
					ContactsConstants.EMAILTYPE);
			mEmailCounter++;
		}
		cursor.close();
	}

	private void getAddress(Cursor cursor, ContentResolver contentResolver,
			String id) {
		mAddCounter = 0;
		cursor = contentResolver.query(ContactsConstants.AURI, null,
				ContactsConstants.AID + " = ? ", new String[] { id }, null);
		while (cursor.moveToNext()) {
			mStreet = Utils.getColumnValue(cursor, ContactsConstants.STREET);
			mCity = Utils.getColumnValue(cursor, ContactsConstants.CITY);
			mState = Utils.getColumnValue(cursor, ContactsConstants.STATE);
			mCountry = Utils.getColumnValue(cursor, ContactsConstants.COUNTRY);
			mPostCode = Utils
					.getColumnValue(cursor, ContactsConstants.POSTCODE);
			mAddCounter++;
		}
		cursor.close();

	}

	/**
	 * Open a printwriter wrapping a FileOutputStream so that we can send output
	 * from a query of the Contacts database to a file on the SD card. Must wrap
	 * the whole thing in a try-catch to catch file not found and i/o
	 * exceptions. Note that since we are writing to external media we must add
	 * a WRITE_EXTERNAL_STORAGE permission to the manifest file. Otherwise a
	 * FileNotFoundException will be thrown.
	 * 
	 * This will set up contact to /sdcard/download/contact.txt if /sdcard is
	 * the root of the external storage. See the project WriteSCard for more
	 * information about writing a file on the SD card.
	 */
	private void saveContacts(String data) {
		File dir = new File(Utils.getExternalStorageRoot() + File.separator
				+ "all_backup");
		if (!dir.exists()) {
			dir.mkdir();
		}
		File file = new File(dir, "phoneData.txt");
		FileOutputStream fout = null;
		PrintWriter pw = null;
		try {
			fout = new FileOutputStream(file);
			pw = new PrintWriter(fout);
			pw.println(data);
			// Flush the PrintWriter to ensure everything pending is output
			// before closing
			pw.flush();
			pw.close();
			fout.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			Log.i("MEDIA",
					"*************** File not found. Did you"
							+ " add a WRITE_EXTERNAL_STORAGE permission to the manifest file? ");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
